package com.share.hope.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import javax.activation.MimetypesFileTypeMap;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.util.UUID;

@Slf4j
public class ImageUtil {

    // 文件的保存路径前缀
    private static final String UPLOAD_DIRECTORY = "D:\\share_hope\\";

    public static String upload(MultipartFile file) throws IOException {
        String fileName = file.getOriginalFilename();
        String filePath = UPLOAD_DIRECTORY + getImgName(fileName);

        // 检查并创建上传目录
        File uploadDir = new File(UPLOAD_DIRECTORY);
        if (!uploadDir.exists()) {
            uploadDir.mkdirs();
        }

        // 将文件保存到服务器
        File serverFile = new File(filePath);
        try (FileOutputStream fos = new FileOutputStream(serverFile)) {
            fos.write(file.getBytes());
            fos.flush();
        } catch (IOException e) {
            throw new IOException("Unable to save file: " + fileName, e);
        }

        // 返回文件的保存路径，可用于在前端显示图片
        log.info("[upload] filePath is: {}", filePath);

        return escapeColonAndBackslash(filePath);
    }

    private static String escapeColonAndBackslash(String input) {
        String escaped = input.replace("\\", "%5C"); // escape backslashes
        escaped = escaped.replace(":", "%3A"); // escape colons
        log.info("[escapeColonAndBackslash] result is: {}", escaped);
        return escaped;
    }


    public static void view(String imagePath, HttpServletResponse response) throws IOException {
        log.info("[view] input path is: {}", imagePath);
        // 读取文件
        File file = new File(imagePath);
        try (FileInputStream fis = new FileInputStream(file)) {
            byte[] data = new byte[(int) file.length()];
            fis.read(data);

            // 获取MIME类型并设置响应头
            MimetypesFileTypeMap mimeTypesMap = new MimetypesFileTypeMap();
            String mimeType = mimeTypesMap.getContentType(file);
            response.setContentType(mimeType);

            // 发送文件响应
            response.getOutputStream().write(data);
            response.flushBuffer();
        } catch (IOException e) {
            throw new IOException("Unable to read file", e);
        }
    }

    private static String getImgName(String str) {
        UUID uuid = UUID.randomUUID();
        String[] parts = str.split("\\.");
        return toBase62(uuid) + "." + parts[1];
    }

    private static String toBase62(UUID uuid) {
        String uuidStr = uuid.toString().replaceAll("-", "");
        BigInteger bigInt = new BigInteger(uuidStr, 16);
        String base62 = "";
        BigInteger radix = BigInteger.valueOf(62);
        while (bigInt.compareTo(BigInteger.ZERO) > 0) {
            BigInteger[] divideAndRemainder = bigInt.divideAndRemainder(radix);
            bigInt = divideAndRemainder[0];
            int digit = divideAndRemainder[1].intValue();
            if (digit < 10) {
                base62 = digit + base62;
            } else if (digit < 36) {
                base62 = (char) ('a' + digit - 10) + base62;
            } else {
                base62 = (char) ('A' + digit - 36) + base62;
            }
        }
        return base62;
    }

}
